package com.example.databinding.BindngAdapter;

import android.graphics.Color;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.databinding.BindingAdapter;

import com.example.databinding.ImageActivity;
import com.example.databinding.R;
import com.squareup.picasso.Picasso;

public class ImageBindingAdapter {

    //image的值传递给函数中哪个参数 应该是根据其变量类型来传递

    //添加bindingAdapter注解 注解的值为xml文件中app:的值
    //加载网络图片
    @BindingAdapter("image")
    public static void setImage(ImageView imageView, String url) {
        if (!TextUtils.isEmpty(url)) {
            Picasso.get()
                    .load(url)
                    .placeholder(R.drawable.ic_launcher_background)
                    .into(imageView);
        } else {
            imageView.setBackgroundColor(Color.BLUE);
        }
    }

    //加载本地图片
    @BindingAdapter("image")
    public static void setImage(ImageView imageView, int resId) {
        if (String.valueOf(resId) != null) {
            imageView.setImageResource(resId);
        } else {
            imageView.setBackgroundColor(Color.BLUE);
        }
    }

    //一个BindingAdapter可以有多个值 requireAll=false表示两个值可以不同时存在
    //当url为空时加载本地图片
    @BindingAdapter(value = {"image", "defaultImageRes"} , requireAll = false)
    public static void setImage(ImageView imageView, String url , int resId ) {
        if (!TextUtils.isEmpty(url)) {
            Picasso.get()
                    .load(url)
                    .placeholder(R.drawable.ic_launcher_background)
                    .into(imageView);
        } else {
            imageView.setImageResource(resId);
        }
    }
}
